import eventBus from "../eventBus";
import debounce from "../utils/debounce.js";
import defaultSrc from "../assets/default.gif";

let imgs = [];

let screenHeight = document.documentElement.clientHeight;

function handleResize() {
    screenHeight = document.documentElement.clientHeight;
    for (const img of imgs) {
        setImage(img);
    }
}

window.onresize = debounce(handleResize);

function setImage(img) {
    const dom = img.dom;
    let rect = dom.getBoundingClientRect();
    if (rect.top >= 0 && rect.top <= screenHeight || rect.bottom >= 0 && rect.bottom <= screenHeight) {
        const realImg = new Image();
        realImg.onload = () => {
            dom.onload = null;
            dom.src = realImg.src;
        }
        realImg.src = img.src;
        imgs = imgs.filter((item) => {
            return item !== img;
        });
    }
}

function handleMainScroll() {
    // 检查imgs中的img是否已经出现在视口
    for (const img of imgs) {
        setImage(img);
    }
}

const handleMainScrollDebounce = debounce(handleMainScroll);

eventBus.$on("mainScroll", handleMainScrollDebounce);

export default {
    inserted(el, binding) {
        const img = {
            dom: el,
            src: binding.value
        };
        imgs.push(img);
        el.onload = () => {
            setImage(img);
        }
        el.src = defaultSrc;
    },
    unbind() {
        imgs = [];
    }
}